package ch02;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * @author Jane
 * @date 2024-03-18 17:13
 */

public class TestDOM4j_365 {
    String url = "src/main/resources/UserMapper.xml";
    Document doc;
    @Before
    public void init() throws DocumentException {
        SAXReader reader = new SAXReader();
        doc = reader.read(url);
    }

    @Test
    public void saxRead(){
        Element rootElement = doc.getRootElement();
        //获取单个
       /* Element mapper = rootElement.element("select");
        String text = mapper.getText();
        System.out.println(text);*/

        //获取多个
        List select = rootElement.elements("select");
        Iterator<Element> its = select.iterator();
        while (its.hasNext()) {
            Element e = its.next();//节点内容
            Iterator<Attribute> attrs = e.attributeIterator();
            while (attrs.hasNext()) {
                Attribute attr = attrs.next();
                System.out.printf("属性：%s \t 值：%s\n",attr.getName(),attr.getText());
            }

            System.out.println(e.getText());
        }

    }
    @Test
    public void addNode(){
        //添加节点
        Element rootElement = doc.getRootElement();
        Element delete = rootElement.addElement("delete");
        delete.addAttribute("id","deleteById");
        delete.addAttribute("resultType","int");
        delete.setText("delete from t_user where uname='张文涛'");
    }

    @After
    public void commit() throws IOException {
        //设置编码
        OutputFormat fmt =OutputFormat.createPrettyPrint();
        fmt.setEncoding("utf-8");
        //保存写入
        XMLWriter writer = new XMLWriter(new FileWriter(url),fmt);
        writer.write(doc);
        writer.close();
    }
}
